package com.keon.jianbao.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.keon.jianbao.AppContext;
import com.keon.jianbao.R;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.enu.MyInfoEdit;
import com.keon.jianbao.ui.widget.CircleImageView;
import com.keon.jianbao.ui.widget.ItemLayout;
import com.keon.jianbao.util.DialogHelp;
import com.keon.jianbao.util.FileUtils;
import com.keon.jianbao.util.ImageUtils;
import com.keon.jianbao.util.JsonUtils;
import com.keon.jianbao.util.StringUtils;
import com.keon.jianbao.util.UILUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.apache.http.Header;
import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;

/**
 * Created by keon on 15/9/6.
 */
public class MyInfoActivity extends BaseActivity {

    public static final int ACTION_TYPE_ALBUM = 0;
    public static final int ACTION_TYPE_PHOTO = 1;
    private final static int CROP = 200;

    private String theLarge;
    private final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/jianbao/Portrait/";
    private Uri origUri;
    private Uri cropUri;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;
    protected ImageLoader imageLoader = ImageLoader.getInstance();

    @Bind(R.id.my_info_avatar_layout)
    LinearLayout llAvatar;
    @Bind(R.id.my_info_avatar)
    CircleImageView ivAvatar;
    @Bind(R.id.my_info_name)
    ItemLayout ilName;
    @Bind(R.id.my_info_sex)
    ItemLayout ilSex;
    @Bind(R.id.my_info_hobby)
    ItemLayout ilHobby;
    @Bind(R.id.my_info_mobile)
    ItemLayout ilmobile;
    @Bind(R.id.my_info_address)
    ItemLayout ilAddress;
    @Bind(R.id.my_info_save)
    Button bSave;

    AsyncHttpResponseHandler alterInfoHandler = new SimpleHandler(this) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
//                    TLog.log(result.getContent() + result.getTips());

//                    User user = new User();
                    MyInfoActivity.showToast(result.getTips());
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    AsyncHttpResponseHandler alterUserFaceHandler = new SimpleHandler(this) {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
//                    ivAvatar.setImageBitmap(protraitBitmap);
                    HashMap hm = JsonUtils.fromJson(result.getContent(), HashMap.class);
                    AppContext.getInstance().setProperty("user.user_face", hm.get("user_face").toString());

//                    Uri uri = Uri.parse(hm.get("user_face").toString());
//                    ivAvatar.setImageURI(uri);
                    ImageLoader.getInstance().displayImage(hm.get("user_face").toString(), ivAvatar, UILUtils.getOptions1());
                    MyInfoActivity.showToast(result.getTips());
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_info;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.my_info;
    }

    @Override
    public void initView() {
        llAvatar.setOnClickListener(this);
        ilName.setOnClickListener(this);
        ilAddress.setOnClickListener(this);
        ilSex.setOnClickListener(this);
        ilHobby.setOnClickListener(this);
        bSave.setOnClickListener(this);
//        ilmobile.setOnClickListener(this);
    }

    @Override
    public void initData() {
//        Api.alter_info(AppContext.getInstance().getProperty("user.code"));

        ilName.setText(AppContext.getInstance().getProperty("user.user_name"));
        ilHobby.setText(AppContext.getInstance().getProperty("user.user_hobby"));
        ilAddress.setText(AppContext.getInstance().getProperty("user.user_address"));
        ilmobile.setText(AppContext.getInstance().getProperty("user.user_mobile"));
        ilSex.setText(AppContext.getInstance().getProperty("user.user_gender"));

//        Uri uri = Uri.parse(AppContext.getInstance().getProperty("user.user_face"));
//        ivAvatar.setImageURI(uri);
        ImageLoader.getInstance().displayImage(AppContext.getInstance().getProperty("user.user_face"), ivAvatar, UILUtils.getOptions1());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        Bundle b = new Bundle();
        switch (id) {
            case R.id.my_info_avatar_layout:
                DialogHelp.getSelectDialog(this, "选择图片", getResources().getStringArray(R.array.choose_picture), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        goToSelectPicture(i);
                    }
                }).show();
                break;
            case R.id.my_info_name:
                b.putInt("type", MyInfoEdit.NAME.getId());
                b.putString("text", ilName.getText());
                jumpForResult(MyInfoEditActivity.class, b, MyInfoEdit.NAME.getId());
                break;
            case R.id.my_info_hobby:
                b.putString("text", ilHobby.getText());
                b.putInt("type", MyInfoEdit.HOBBY.getId());
                jumpForResult(MyInfoEditActivity.class, b, MyInfoEdit.HOBBY.getId());
                break;
            case R.id.my_info_address:
                b.putString("text", ilAddress.getText());
                b.putInt("type", MyInfoEdit.ADDRESS.getId());
                jumpForResult(MyInfoEditActivity.class, b, MyInfoEdit.ADDRESS.getId());
                break;
            case R.id.my_info_save:
                Api.alter_info(AppContext.getInstance().getProperty("user.code"), ilHobby.getText(),
                        ilName.getText(), ilAddress.getText(), ilSex.getText(), ilmobile.getText(), "", alterInfoHandler);
                break;
            case R.id.my_info_sex:
                final String[] sexs = getResources().getStringArray(R.array.gender);
                DialogHelp.getSelectDialog(this, sexs, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ilSex.setText(sexs[which]);
                    }
                }).show();
                break;
            case R.id.my_info_mobile:
                b.putString("text", ilmobile.getText());
                b.putInt("type", MyInfoEdit.MOBILE.getId());
                jumpForResult(MyInfoEditActivity.class, b, MyInfoEdit.MOBILE.getId());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = new Bundle();
            if (data != null) {
                bundle = data.getExtras();
            }

            if (requestCode == MyInfoEdit.NAME.getId()) {
                String text = bundle.getString("text");
                ilName.setText(text);
            } else if (requestCode == MyInfoEdit.HOBBY.getId()) {
                String text = bundle.getString("text");
                ilHobby.setText(text);
            } else if (requestCode == MyInfoEdit.ADDRESS.getId()) {
                String text = bundle.getString("text");
                ilAddress.setText(text);
            } else if (requestCode == MyInfoEdit.MOBILE.getId()) {
                String text = bundle.getString("text");
                ilmobile.setText(text);
            } else {
                switch (requestCode) {
                    case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
                        startActionCrop(origUri);// 拍照后裁剪
                        break;
                    case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
                        if (data != null) {
                            startActionCrop(data.getData());// 选图后裁剪
                        } else {
                            startActionCrop(origUri);
                        }

                        break;
                    case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
                        uploadNewPhoto();
                        break;
                }
            }
        }
    }

    private void goToSelectPicture(int position) {
        switch (position) {
            case ACTION_TYPE_ALBUM:
                startImagePick();
                break;
            case ACTION_TYPE_PHOTO:
                startTakePhoto();
                break;
            default:
                break;
        }
    }

    /**
     * 选择图片裁剪
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/jianbao/Camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            showToastShort("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = "jianbao_" + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        theLarge = savePath + fileName;// 该照片的绝对路径

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }


    /**
     * 拍照后裁剪
     *
     * @param data 原始图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            showToast("无法保存上传的头像，请检查SD卡是否挂载");
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getAbsoluteImagePath(this, uri);
        }
        String ext = FileUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "jianbao_crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }

    private void uploadNewPhoto() {
        showWaitDialog("正在上传头像...");

        // 获取头像缩略图
        if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
            protraitBitmap = ImageUtils
                    .loadImgThumbnail(protraitPath, 100, 100);
        } else {
            showToast("图像不存在，上传失败");
        }
        if (protraitBitmap != null) {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            protraitBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//            byte[] bytes = baos.toByteArray();
//            byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
//            String encodeString = new String(encode);
//            DinnerApi.editUserInfo("", encodeString, "jpg", mEditUserInfohandler);
            try {
                Api.alter_user_face(AppContext.getInstance().getProperty("user.code"), protraitFile, alterUserFaceHandler);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
